import purchaseReceiptService, { type PageListReq } from "@/api/services/wms/purchaseReceiptService";
import warehouseService from "@/api/services/wms/warehouseService";
import CustomTable from "@/components/grid/CustomTable";
import TableDictTag from "@/components/grid/TableDictTag";
import useDictionary from "@/hooks/system/useDictionary";
import { t } from "@/locales/i18n";
import { FileTextOutlined, UserAddOutlined } from "@ant-design/icons";
import { Button, Card, Col, DatePicker, Drawer, Form, Input, Row, Select, Space, Spin, Tabs } from "antd";
import type { ColumnsType } from "antd/es/table";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import type { WmsWarehouse } from "../warehouse/entity";
import WmsPurchaseReceiptDetailPage, { type WmsPurchaseReceiptDetailHandles } from "./detail";
import type { WmsPurchaseReceipt } from "./entity";
import SinglePurchaseOrderSelect from "@/pages/components/selector/SinglePurchaseOrderSelect";
import WmsPurchaseReceiptDrawer from "./ReceiptDrawer";

const { TextArea } = Input;

export default function WmsPurchaseReceiptPage() {
	const detailRef = useRef<WmsPurchaseReceiptDetailHandles>(null);

	const [loading, setLoading] = useState(false);
	const [submitLoading, setSubmitLoading] = useState(false);
	const [queryParams, setQueryParams] = useState<PageListReq>({
		receiptCode: undefined,
		purchaseOrderCode: undefined,
		supplierId: undefined,
		warehouseId: undefined,
		status: undefined,
		page: 1,
		pageSize: 10,
	});
	const [total, setTotal] = useState(0);
	const [list, setList] = useState<WmsPurchaseReceipt[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [drawerVisible, setDrawerVisible] = useState(false);
	const [receiptDrawerVisible, setReceiptDrawerVisible] = useState(false);
	const [editingData, setEditingData] = useState<WmsPurchaseReceipt | null>(null);
	const [form] = Form.useForm();
	const poCode = Form.useWatch("purchaseOrderCode", form);
	const [isView, setIsView] = useState(true);
	const [poSelectVisiable, setPOSelectVisiable] = useState(false);
	const [warehouseList, setWarehouseList] = useState<WmsWarehouse[]>([]);

	//动态设置表格高度
	const [tableScrollY, setTableScrollY] = useState(0);
	const PAGE_OFFSET_HEIGHT = 405;
	const updateTableHeight = () => {
		const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
		setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
	};

	const orderStatusOptions = useDictionary("purchase_receipt_status");

	useEffect(() => {
		updateTableHeight(); // 初始化
		window.addEventListener("resize", updateTableHeight);
		return () => window.removeEventListener("resize", updateTableHeight);
	}, []);

	const columns: ColumnsType<WmsPurchaseReceipt> = [
		{
			title: "收料单编号",
			width: 120,
			key: "receiptCode",
			dataIndex: "receiptCode",
		},
		{
			title: "采购订单号",
			width: 120,
			key: "purchaseOrderCode",
			dataIndex: "purchaseOrderCode",
		},
		{
			title: "供应商",
			width: 120,
			key: "supplierName",
			dataIndex: "supplierName",
		},
		{
			title: "仓库",
			width: 120,
			key: "warehouseName",
			dataIndex: "warehouseName",
		},
		{
			title: "入库日期",
			width: 120,
			key: "receiptDate",
			dataIndex: "receiptDate",
		},
		{
			title: "单据状态",
			width: 120,
			key: "status",
			dataIndex: "status",
			render: (_, record) => <TableDictTag dictCode="purchase_receipt_status" value={record.status ?? ""} />,
		},
		{
			title: "备注",
			width: 120,
			key: "remark",
			dataIndex: "remark",
		},
		{
			title: "操作",
			fixed: "right",
			key: "operation",
			align: "center",
			width: 100,
			render: (_, record) => (
				<Space>
					<Button type="link" onClick={() => handleView(record)}>
						{t("common.view")}
					</Button>
					<Button type="link" onClick={() => handleEdit(record)}>
						{t("common.edit")}
					</Button>
				</Space>
			),
		},
	];

	useEffect(() => {
		getWarehouseList();
	}, []);

	//加载表格数据
	const fetchPageList = () => {
		setLoading(true);
		purchaseReceiptService
			.pageList(queryParams)
			.then((res) => {
				setList(res.records);
				setTotal(res.total);
			})
			.catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	// 获取仓库下拉数据
	const getWarehouseList = () => {
		warehouseService
			.selectList()
			.then((res) => {
				setWarehouseList(res);
			})
			.catch((error) => {
				console.error(error);
				toast.error("加载仓库数据失败！");
			});
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		fetchPageList();
	}, [queryParams]);

	//选择其他页
	const handlePageChange = (newPage: number, newPageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page: newPage,
			pageSize: newPageSize,
		}));
	};

	//触发编辑按钮
	const handleEdit = (wmsPurchaseReceipt: WmsPurchaseReceipt) => {
		setEditingData(wmsPurchaseReceipt);
		form.setFieldsValue({
			...wmsPurchaseReceipt,
			receiptDate: wmsPurchaseReceipt.receiptDate ? dayjs(wmsPurchaseReceipt.receiptDate) : undefined,
		});
		setDrawerVisible(true);
		setIsView(false);
	};

	//触发视图按钮
	const handleView = (wmsPurchaseReceipt: WmsPurchaseReceipt) => {
		setEditingData(wmsPurchaseReceipt);
		setReceiptDrawerVisible(true);
		setIsView(true);
	};

	//提交表单数据
	const handleSubmit = async (values: WmsPurchaseReceipt) => {
		try {
			setSubmitLoading(true);

			//物料入库单行
			const deleteDetailIds = detailRef.current?.getDeleteIds();
			const addDetails = detailRef.current?.getAddList();
			const updateDetails = detailRef.current?.getUpdateList();

			const data = {
				...values,
				id: editingData?.id,
				receiptDate: values.receiptDate ? dayjs(values.receiptDate).format("YYYY-MM-DD") : undefined,
				deleteDetailIds: deleteDetailIds,
				addDetails: addDetails,
				updateDetails: updateDetails,
			};
			if (editingData) {
				await purchaseReceiptService.update(data);
				toast.success("更新采购入库单主成功");
			} else {
				await purchaseReceiptService.add(data);
				toast.success("创建采购入库单主成功");
			}
			setDrawerVisible(false);
			setEditingData(null);
			form.resetFields();
			fetchPageList();
		} catch (error) {
			toast.error(`保存失败: ${error.message}`);
		} finally {
			setSubmitLoading(false);
		}
	};

	const handleDrawerClose = () => {
		setDrawerVisible(false);
		setEditingData(null);
		form.resetFields();
	};

	const handleAdd = () => {
		setEditingData(null);
		form.resetFields();
		form.setFieldValue("status", "created");
		setDrawerVisible(true);
		setIsView(false);
	};

	const handleDelete = async () => {
		try {
			setLoading(true);
			await purchaseReceiptService.remove(selectedRowKeys);
			toast.success("删除采购入库单主成功");
			setSelectedRowKeys([]);
			fetchPageList();
		} catch (error) {
			toast.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	const handleReceipt = () => {
		if (selectedRowKeys.length !== 1) {
			toast.error("请选择一条数据进行来料接收");
			return;
		}
		const wmsPurchaseReceiptId = selectedRowKeys[0];
		const wmsPurchaseReceipt = list.find((item) => item.id === wmsPurchaseReceiptId);
		setEditingData(wmsPurchaseReceipt || null);

		setReceiptDrawerVisible(true);
		setIsView(false);
	};

	const showPOSelect = () => {
		setPOSelectVisiable(true);
	};
	const handleSelectPO = (po: any) => {
		console.log("选中采购订单", po);
		form.setFieldsValue({
			purchaseOrderId: po?.id,
			purchaseOrderCode: po?.po_code,
			supplierId: po?.supplier_id,
			supplierName: po?.supplier_name,
		});
		setPOSelectVisiable(false);
	};

	return (
		<Spin spinning={submitLoading} tip="数据提交中..." size="large">
			<Card className="mb-4">
				<Form
					layout="inline"
					onFinish={(values) => {
						setQueryParams((prev) => ({
							...prev,
							...values,
							page: 1,
						}));
					}}
				>
					<Form.Item name="receiptCode" label="收料单编号">
						<Input placeholder="请输入收料单编号" allowClear />
					</Form.Item>
					<Form.Item name="purchaseOrderCode" label="采购订单号">
						<Input placeholder="请输入采购订单号" allowClear />
					</Form.Item>
					<Form.Item name="status" label="单据状态">
						<Select options={orderStatusOptions} allowClear style={{ width: 150 }} />
					</Form.Item>
					<Form.Item>
						<Button type="primary" htmlType="submit">
							查询
						</Button>
						<Button
							className="ml-2"
							onClick={() => {
								setQueryParams({ page: 1, pageSize: 10 });
							}}
						>
							重置
						</Button>
					</Form.Item>
				</Form>
			</Card>
			<div className="h-4" />
			<Card>
				<CustomTable
					loading={loading}
					columnsConfig={columns}
					dataSource={list}
					total={total}
					selectedRowKeys={selectedRowKeys}
					setSelectedRowKeys={setSelectedRowKeys}
					current={queryParams.page}
					pageSize={queryParams.pageSize}
					onRefresh={fetchPageList}
					onPageChange={handlePageChange}
					selectable
					toolbarButtons={
						<>
							<Button type="primary" onClick={handleAdd}>
								新增
							</Button>
							<Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
								删除
							</Button>
							<Button type="primary" disabled={selectedRowKeys.length !== 1} onClick={handleReceipt}>
								来料接收
							</Button>
						</>
					}
					scroll={{ y: tableScrollY }}
				/>
			</Card>
			<Drawer
				title={editingData ? "编辑采购入库单主" : "新增采购入库单主"}
				width={900}
				open={drawerVisible}
				onClose={handleDrawerClose}
				footer={
					<div className="flex justify-end gap-2">
						<Button onClick={handleDrawerClose}>取消</Button>
						{!isView && (
							<Button type="primary" loading={submitLoading} onClick={() => form.submit()}>
								确定
							</Button>
						)}
					</div>
				}
			>
				<Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} onFinish={handleSubmit} disabled={isView}>
					<Row gutter={24}>
						<Col span={12}>
							<Form.Item name="receiptCode" label="收料单编号">
								<Input placeholder="编号自动生成" disabled />
							</Form.Item>
						</Col>
						<Col span={12}>
							<Form.Item name="purchaseOrderId" label="采购订单号" hidden>
								<Input />
							</Form.Item>
							<Form.Item name="purchaseOrderCode" label="采购订单号">
								<Input.Search
									placeholder="请输入采购订单号"
									allowClear
									enterButton={<FileTextOutlined />}
									onSearch={showPOSelect}
								/>
							</Form.Item>
						</Col>
					</Row>
					<Row gutter={24}>
						<Col span={12}>
							<Form.Item name="supplierId" label="供应商" hidden>
								<Input />
							</Form.Item>
							<Form.Item name="supplierName" label="供应商">
								<Input disabled />
							</Form.Item>
						</Col>
						<Col span={12}>
							<Form.Item name="warehouseId" label="仓库">
								<Select
									options={warehouseList.map((item) => ({
										label: item.name,
										value: item.id,
									}))}
									allowClear
								/>
							</Form.Item>
						</Col>
					</Row>
					<Row gutter={24}>
						<Col span={12}>
							<Form.Item name="receiptDate" label="入库日期">
								<DatePicker style={{ width: "100%" }} onChange={(date, dateString) => dateString} />
							</Form.Item>
						</Col>
						<Col span={12}>
							<Form.Item name="status" label="单据状态">
								<Select options={orderStatusOptions} disabled />
							</Form.Item>
						</Col>
					</Row>
					<Row gutter={24}>
						<Col span={24}>
							<Form.Item name="remark" label="备注" labelCol={{ span: 3 }} wrapperCol={{ span: 21 }}>
								<TextArea />
							</Form.Item>
						</Col>
					</Row>

					<Tabs
						defaultActiveKey="1"
						items={[
							{
								key: "1  ",
								label: "物料入库单行",
								children: <WmsPurchaseReceiptDetailPage ref={detailRef} parentId={editingData?.id} poCode={poCode} />,
							},
						]}
					/>
				</Form>
			</Drawer>

			{/* 供应商选择器 */}
			<SinglePurchaseOrderSelect
				open={poSelectVisiable}
				onCancel={() => setPOSelectVisiable(false)}
				onOk={(item) => handleSelectPO(item)}
			/>

			{/* 来料入库 */}
			<WmsPurchaseReceiptDrawer
				isView={isView}
				parentId={editingData?.id}
				formData={editingData}
				drawerVisible={receiptDrawerVisible}
				handleDrawerClose={() => setReceiptDrawerVisible(false)}
			/>
		</Spin>
	);
}
